Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
"this" keyword with Prototype JS

I'm confused with the "this"keyword in JS. I understand that rabbit's prototype is animal and the "this" keyword in rabbit.isSleeping should refer to rabbit but I thought the animal.isSleeping should refer to animal I don't understand why it's undefined? Could someone explain?

let animal = {
  walk() {
    if (!this.isSleeping) {
      alert(`I walk`);
    }
  },
  sleep() {
    this.isSleeping = true;
  }
};

let rabbit = {
  name: "White Rabbit",
  __proto__: animal
};


rabbit.sleep();

alert(rabbit.isSleeping); // true
alert(animal.isSleeping)
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When a property is assigned to an object - here, when you do

this.isSleeping = true;

The engine will first examine the instance, then its internal prototype, and so on up to the beginning of the prototype chain - to identify the first such object that has an isSleeping property. If an object is found, and it's a setter, the setter is invoked. Otherwise, no matter where the property is found, the instance is assigned the property (as a data property, of course).

When you do

rabbit.sleep();

the instance is rabbit - that's the this inside the method. And there are no isSleeping setters, so

  sleep() {
    this.isSleeping = true;
  }

results in the instance - the rabbit object - receiving the property. So the animal object remains unchanged.

Unless there are getters/setters involved somewhere, doing

someObj.someProp = someVal

will always and only ever result in someObj being mutated, while keeping its internal prototype(s) unchanged.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda